package com.meida.module.bus.provider.service.impl;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.db.sql.SqlBuilder;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.meida.common.mybatis.base.service.impl.BaseServiceImpl;
import com.meida.common.mybatis.entity.EntityMap;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.mybatis.query.CriteriaSave;
import com.meida.common.mybatis.query.CriteriaUpdate;
import com.meida.common.utils.FlymeUtils;
import com.meida.module.admin.client.entity.BaseUser;
import com.meida.module.bus.client.entity.*;
import com.meida.module.bus.provider.api.service.SyncSrmService;
import com.meida.module.bus.provider.api.util.ApiConstants;
import com.meida.module.bus.provider.mapper.BusPurchaseMapper;
import com.meida.module.bus.provider.service.BusMaterialSrmSubService;
import com.meida.module.bus.provider.service.BusPurchaseService;
import com.meida.module.bus.provider.service.BusVersionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 采购计划表接口实现类
 *
 * @author flyme
 * @date 2020-10-19
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BusPurchaseServiceImpl extends BaseServiceImpl<BusPurchaseMapper, BusPurchase> implements BusPurchaseService {
    @Autowired
    private BusVersionService busVersionService;

    @Autowired
    private BusMaterialSrmSubService srmSubService;
    @Autowired
    private SyncSrmService syncSrmService;

    @Override
    public ResultBody beforeAdd(CriteriaSave cs, BusPurchase purchase, EntityMap extra) {
        return ResultBody.ok();
    }


    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody beforePageList(CriteriaQuery<BusPurchase> cq, BusPurchase purchase, EntityMap requestMap) {
        //查询当前项目所在版本，查询相应的100材料或者200材料申请记录
        cq.createJoin(BusPurchaseDetails.class).setMainField("purchaseId").setJoinField("purchaseId");
        if (FlymeUtils.isNotEmpty(requestMap.get("versionType")) && requestMap.get("versionType").equals("1")) {
            cq.select("bmplan.majorName,bmplan.majorCode,bmplan.packageNo,bmplan.versionId,bmplan.materialId,bmplan.packageName,project.projectName,project.projectCode,user.userName,bmplan.applayStatus,bpd.purchaseDetailsId");
            cq.createJoin(BusMaterialPlan100.class).setMainAlias("bmplan").setMainField("materialId").setMainAlias("bpd").setJoinField("materialPlanId");
//            cq.createJoin(BusMaterial.class).setMainAlias("material").setMainField("materialId").setMainAlias("bmplan").setJoinField("materialId");
        }
        if (FlymeUtils.isNotEmpty(requestMap.get("versionType")) && requestMap.get("versionType").equals("2")) {
            cq.select("bmep.majorName,bmep.majorCode,bmep.packageNo,bmep.versionId,bmep.materialId,bmep.packageName,project.projectName,project.projectCode,user.userName,bmep.applayStatus,bpd.purchaseDetailsId");
            cq.createJoin(BusMaterialPlan200.class).setMainAlias("bmep").setMainField("materialId").setMainAlias("bpd").setJoinField("materialPlanId");
//            cq.createJoin(BusMaterial.class).setMainAlias("material").setMainField("materialId").setMainAlias("bmep").setJoinField("materialId");
        }
        cq.createJoin(BusProject.class).setJoinField("projectId").setMainField("projectId");
        cq.createJoin(BaseUser.class).setMainField("userId").setJoinField("userId");
        cq.groupBy("bpd.purchaseId");
        cq.orderByDesc("purchase.createTime");
//        cq.eq("user.userId", OpenHelper.getUserId());
        cq.eq("project.projectId", requestMap.get("projectId"));
        return ResultBody.ok();
    }

    @Override
    public ResultBody getSyncSrmOpenData(Map params) {
        JSONObject filterObj = JSONUtil.parseObj(params.get("params"));
//        BusVersion busVersion = busVersionService.getById(filterObj.getLong("versionId"));
        CriteriaQuery cq = new CriteriaQuery<>(BusPurchaseDetails.class);
        cq.createJoin(BusMasterAlldataView.class).setJoinField("packagePlanId").setMainField("materialId").setJoinType(SqlBuilder.Join.INNER);
        cq.createJoin(BusMaterialSrmSub.class).setJoinField("purchaseDetailsId").setMainField("purchaseDetailsId").setJoinType(SqlBuilder.Join.INNER);
        cq.eq("bpd.projectId", filterObj.getLong("projectId"));
        cq.eq("bmss.orderFlg", ApiConstants.ORDER_FLG_ON);
        cq.eq("bmss.sycnFlgForOpen", ApiConstants.ORDER_OPEN_FLG_SYNC_ING);
        cq.addSelect(BusPurchaseDetails.class, "*");
        cq.addSelect(BusMasterAlldataView.class, "*");
        cq.addSelect(BusMaterialSrmSub.class, "*");
        cq.orderByAsc("bmss.contractRowno");
//        cq.groupBy("bpd.purchaseId");
        List<EntityMap> entityMapList = selectEntityMap(cq);
        return ResultBody.ok(entityMapList);
    }

    @Override
    public ResultBody syncDataOpen(Map params) {
        JSONObject filterObj = JSONUtil.parseObj(params.get("params"));
        List<EntityMap> listentityMap = JSON.parseArray(String.valueOf(params.get("dataArray")), EntityMap.class);

        List<BusMaterialSrmSub> srmList = Lists.newArrayList();
        if (0 < listentityMap.size()) {
            listentityMap.stream().forEach(obj -> {
                BigDecimal orderThisTimeQty = obj.getBigDecimal("orderThisTimeQty");
                if (null != orderThisTimeQty && BigDecimal.ZERO.compareTo(orderThisTimeQty) < 0) {
                    BusMaterialSrmSub materialSrmSub = srmSubService.getById(obj.getLong("busMaterialSrmSubId"));
//                materialSrmSub.setRowids(obj.getInt("rowids"));
//                materialSrmSub.setVer(obj.getInt("ver"));
//                materialSrmSub.setBusMaterialSrmSubId(obj.getLong("busMaterialSrmSubId"));
                    // 已下数量
                    materialSrmSub.setOrderOutQty(NumberUtil.add(materialSrmSub.getOrderOutQty(), materialSrmSub.getOrderThisTimeQty()));
                    // 剩余数量
                    materialSrmSub.setOrderSurplusQty(materialSrmSub.getOrderSurplusQty().subtract(materialSrmSub.getOrderThisTimeQty()));
                    materialSrmSub.setOrderThisTimeQty(obj.getBigDecimal("orderThisTimeQty"));
                    materialSrmSub.setSycnFlgForOpen(ApiConstants.ORDER_OPEN_FLG_SYNC_OK);
                    srmList.add(materialSrmSub);
                }
            });

            if (0 < srmList.size()) {
                srmSubService.updateBatchById(srmList);
                syncSrmService.openOrderRequest(srmList);
            }
        }
        return ResultBody.ok();
    }

    /**
     * 更新申请记录审批状态
     * @param purchaseId
     * @param state
     */
    @Override
    public void updateApprovalState(Long purchaseId, int state) {
        CriteriaUpdate<BusPurchase> cu = new CriteriaUpdate();
        cu.eq("purchaseId", purchaseId);
        cu.set("state", state);
        update(cu);
    }
}
